﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PluginService.DB.Contract;
using PluginService.DB.Service;
using PluginService.DB.Model;
using CommonProjects.FaceFeatureContex;
using PluginService.Common.Model;


namespace PluginService
{
    /// <summary>
    /// 当服务启动时从数据库中提取黑名单到比对线程中
    /// </summary>
    public class FDNamedPiepAndSaveBlankHelper:FaceDeteiveServiceNamedPipeHelper
    {
        protected IBlankFeatureService _blankFeatureDaoService = new BlankFeatureService();
        protected int _pageSize = 1;

        protected override void BlankPipe_ClientMessage(NamedPipeWrapper.NamedPipeConnection<PluginMessage<FaceFeatureItem>, PluginMessage<FaceFeatureItem>> connection, PluginMessage<FaceFeatureItem> message)
        {
            if(message!=null)
            {
                base.BlankPipe_ClientMessage(connection, message);
                SaveBlankToDB(message.MessageBody);
            }
            
            //try
            //{
            //    var model = new DB.Model.BlankFeature()
            //    {
            //        CreateTime = DateTime.Now.ToString(),
            //        Feture = message.MessageBody.Feature,
            //        Name = message.MessageBody.Id,
            //        ImageHttpUrl = message.MessageBody.HttpImageUrl,
            //        ImageBase64 = message.MessageBody.ImageBase64Str,
            //        Valid = 1.0f
            //    };

            //    if (string.IsNullOrEmpty(model.ImageBase64) && message.MessageBody.ImageArray != null)
            //    {
            //        model.ImageBase64 = Convert.ToBase64String(message.MessageBody.ImageArray);
            //    }
            //    _blankFeatureDaoService.InsertBlankFeature(model);
            //}
            //catch (Exception ex)
            //{
            //    _log.Error("保存到数据库黑名单错误");
            //    _log.Error(ex);
            //}
        }

        protected virtual void SaveBlankToDB(FaceFeatureItem faceFeatureItem)
        {
            if (faceFeatureItem != null)
            {
                try
                {
                    var model = new DB.Model.BlankFeature()
                    {
                        CreateTime = DateTime.Now.ToString(),
                        Feture = faceFeatureItem.Feature,
                        Name = faceFeatureItem.Name,
                        ImageHttpUrl = faceFeatureItem.HttpImageUrl,
                        ImageBase64 = faceFeatureItem.ImageBase64Str,
                        CustomId=faceFeatureItem.CustomeId,
                        Guid = faceFeatureItem.Id,
                        Valid = 1.0f
                    };

                    if (string.IsNullOrEmpty(model.ImageBase64) && faceFeatureItem.ImageArray != null)
                    {
                        model.ImageBase64 = Convert.ToBase64String(faceFeatureItem.ImageArray);
                    }
                    _blankFeatureDaoService.InsertBlankFeature(model);
                }
                catch (Exception ex)
                {
                    _log.Error("保存到数据库黑名单错误");
                    _log.Error(ex);
                }
            }
            
        }

        protected virtual void HandOnAddBlankComplete(bool result,string error)
        {
            _commandPipeServer.PushMessage(new CommandModel()
            {
                CommandType = CommandType.AddBlank,
                CommandBody =Newtonsoft.Json.JsonConvert.SerializeObject( new CommandResult() {
                    Result=result,
                    Error=error
                }),
            });
        }

        protected override void InitBlankData()
        {
            base.InitBlankData();
            int pageIndex = 1;
            IList<BlankFeature> blankFeatures = GetBkankFeatureFormDB(pageIndex, _pageSize);
            
            if (blankFeatures != null)
            {
                AddBlanFeatureToFaceDeteiveManager(blankFeatures);
                while (true)
                {
                    pageIndex++;
                    blankFeatures = GetBkankFeatureFormDB(pageIndex, _pageSize);
                    if (blankFeatures != null && blankFeatures.Count > 0)
                    {
                        AddBlanFeatureToFaceDeteiveManager(blankFeatures);
                    }
                    else
                    {
                        break;
                    }
                    
                }
            }

        }

        private IList<BlankFeature> GetBkankFeatureFormDB(int pageIndex,int pageSize)
        {
            IList<BlankFeature> blankFeatures = null;
            try
            {
                blankFeatures = _blankFeatureDaoService.GetBlankFeatures(new DB.Model.BlankFeatureQP()
                {
                    PageIndex = pageIndex,
                    PageSize = _pageSize
                });
            }
            catch (Exception ex)
            {
                _log.Error("从数据库中获取黑名单错误");
                _log.Error(ex);
            }
            return blankFeatures;
        }

        private void AddBlanFeatureToFaceDeteiveManager(IList<BlankFeature> blanks)
        {
            if (blanks != null)
            {
                foreach (var b in blanks)
                {
                    try
                    {
                        if (_faceDeteiveManager != null)
                        {
                            _faceDeteiveManager.AddStorageCacheItem(new FaceFeatureItem(b.Name, b.Feture, Convert.ToDateTime(b.CreateTime)));
                        }
                        
                        
                    }
                    catch(FormatException ex)
                    {
                        _log.Error("数据库中存储黑名单数据中，CreateTime错误");
                        _log.Error(ex);
                    }
                    
                }
            }
        }
    }
}
